package com.dg.admodule.adbutton;
import java.util.Timer;
import java.util.TimerTask;


import com.dg.admodule.IAdClickListener;
import com.smaato.SmaatoAd;

import net.rim.blackberry.api.browser.Browser;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.GIFEncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;

/**
 * An example utility class that will display a SmaatoAd, animating if possible, 
 * and also makes the ad clickable.
 */
public class SmaatoAdField extends BitmapField
{
	private IAdClickListener listener = null;
	// Animated GIF variables
	private static final int GIF_FRAME_DELAY_UNITS_MS = 10; // GIF frame delay is in 1/100 of a second
	private Timer iAnimationTimer;
	private GIFEncodedImage iAnimatedGif;
	private int iFrameIndex = 0;
	private Bitmap iDrawingSurface;
	private Bitmap banner;
	private Graphics iGraphics;
	
	// The current Ad
	private SmaatoAd iAd;
	private boolean focused;

	public SmaatoAdField(SmaatoAd ad, Bitmap defBannerImg) 
	{
		this(ad, 0, defBannerImg);
	}

	public SmaatoAdField(SmaatoAd ad, long style, Bitmap defBannerImg)
	{
		// Set FOCUSABLE to allow ad to be clicked
		// We can't set the image here as more processing is required
		super(null, Field.FOCUSABLE | style);
		this.banner = defBannerImg;
		setupSmaatoAd(ad);
	}
	
	// Set a new ad
	public void setSmaatoAd(SmaatoAd ad)
	{
		// If we already have an animated GIF displayed close it safely
		if(isAnimated())
		{
			stop();
			iAnimatedGif = null;
		}
		
		setupSmaatoAd(ad);
	}
	
	private void setupSmaatoAd(SmaatoAd ad)
	{
		iAd = ad;
		
		if(iAd != null)
		{
			// if we have a GIF check to see if it can be animated
			if(iAd.getImage() instanceof GIFEncodedImage)
			{
				if(iAd.getImage().getFrameCount() > 1)
				{
					// We have an animated GIF
					iAnimationTimer = new Timer();
					iAnimatedGif = (GIFEncodedImage) iAd.getImage();
					iDrawingSurface = new Bitmap(iAnimatedGif.getWidth(), iAnimatedGif.getHeight());
					iGraphics = new Graphics(iDrawingSurface);
					iFrameIndex = 0;
					updateBitmapField();
				}
				else
				{
					// This GIF is not animated, simply set the image
					this.setBitmap(iAd.getImage().getBitmap());
				}
			}
			else
			{
				// Set the image
				this.setBitmap(iAd.getImage().getBitmap());
			}
		}
		else
		{
			// Clear the ad
			//this.setBitmap(null);
			try {
				this.setBitmap(banner);
			} catch (Exception e) {
				this.setBitmap(null);
			}
		}
	}

	// called with ACTION_INVOKE when field is clicked on - works on both touch and non-touch
	protected boolean invokeAction(int action) 
	{
		if (action == ACTION_INVOKE) 
		{
			if (iAd != null) {
				iAd.clickThrough();
			} else {
				Browser.getDefaultSession().displayPage("http://appworld.blackberry.com/webstore/search/k2media%20labs/");
			}
			if (this.listener != null) {
				this.listener.adClicked(true);
			}
			return true;
		}
		else 
		{
			return super.invokeAction(action);
		}
	}

	// Animates the image
	private void updateBitmapField() 
	{
		try 
		{
			drawNextFrame(iFrameIndex);
			synchronized (UiApplication.getEventLock()) 
			{
				setBitmap(iDrawingSurface);
			}
			
			int frameDelayMilliS = iAnimatedGif.getFrameDelay(iFrameIndex)* GIF_FRAME_DELAY_UNITS_MS;
			iAnimationTimer.schedule(new TimerTask() 
			{
				public void run() 
				{
					updateBitmapField();
				}
			}, frameDelayMilliS);
			
			if (++iFrameIndex >= iAnimatedGif.getFrameCount()) 
			{
				iFrameIndex = 0;
			}
		}
		catch (Exception e) 
		{
			// Couldn't update animation
		}
	}
	
	private void drawNextFrame(int frameIndex)
	{
		int transition = iAnimatedGif.getFrameTransition(frameIndex);
		Bitmap frame = iAnimatedGif.getBitmap(frameIndex);
		
		if(transition == GIFEncodedImage.TRANSITION_REPLACE)
		{
			iGraphics.setBackgroundColor(iAnimatedGif.getBackgroundColor());
			iGraphics.clear();
		}

		iGraphics.drawBitmap(iAnimatedGif.getFrameLeft(frameIndex), iAnimatedGif.getFrameTop(frameIndex), frame.getWidth(), frame.getHeight(), frame, 0, 0);
	}
	
	// Returns true if current ad is animated
	public boolean isAnimated()
	{
		return (iAnimatedGif != null);
	}

	// Call this before letting the object go out of scope
	public void stop() 
	{
		iAnimationTimer.cancel();
	}
	
	protected void drawFocus(Graphics graphics, boolean on) {
	}
	
	protected void paint(Graphics graphics) {
		super.paint(graphics);
		if (this.focused){
			graphics.setColor(Color.RED);
			graphics.drawRect(0, 0, getWidth(), getHeight());
		}
	}
	
	protected void onFocus(int direction) {
		focused = true;
		invalidate();
		super.onFocus(direction);
	}
	
	protected void onUnfocus() {
		focused = false;
		invalidate();
		super.onUnfocus();
	}
	
	public boolean getFocusState(){
		return this.focused;
	}
	
	public boolean initClick(){
		return this.invokeAction(ACTION_INVOKE);
	}

	public IAdClickListener getListener() {
		return listener;
	}

	public void setListener(IAdClickListener listener) {
		this.listener = listener;
	}
}
